package com.web.controller;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lenovo
 * @Description
 * @Date2025-3-3 17:02
 * 解决跨域问题的过滤器
 * /*代表所有servlet
 */
@WebFilter("/*")
public class CORSFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /**
     * 过滤方法
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //转换响应类型
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        // 设置响应类型
        resp.setContentType("application/json;charset=UTF-8");

        //设置响应头 Access-Control-Allow-Origin 代表允许的域 * 所有
        resp.setHeader("Access-Control-Allow-Origin","*");
        //允许的方法
        resp.setHeader("Access-Control-Allow-Methods","*");
        //允许的响应头
        resp.setHeader("Access-Control-Allow-Headers","*");
        //通过过滤
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
    }
}